﻿using System;
using System.Web;

namespace MvcCommonLib.Session {
    public class SessionProvider<X> : ISessionProvider<X> {
        private HttpSessionStateBase m_session;
        public SessionProvider(HttpSessionStateBase session) {
            m_session = session;
        }
        public void Clear() {
            foreach (var item in m_session) {
                var disposalItem = item as IDisposable;
                if (disposalItem != null) {
                    disposalItem.Dispose();
                }
            }
            m_session.Clear();
        }

        public T Get<T>(X key) {
            if (m_session == null) {
                return default(T);
            }
            var item = m_session[key.ToString()];
            if (item == null) {
                return default(T);
            }
            return (T)item;
        }

        public void Set<T>(X key, T value) {
            var item = m_session[key.ToString()];
            
            m_session[key.ToString()] = value;
            if (item != null && item is IDisposable) {
                ((IDisposable)item).Dispose();
            }
        }

        public void Abandon() {
            m_session.Abandon();
        }
        public void Remove(X key) {
            m_session.Remove(key.ToString());
        }
    }
}
